package com.wichatbackapi.service;

import com.wichatbackapi.domain.LoginUser;
import com.wichatbackapi.domain.doa.SysUser;
import com.wichatbackapi.utils.StringUtils;
import com.wichatbackapi.utils.enums.UserStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private SysUserService userService;
    @Autowired
    private SysPasswordService passwordService;
//    @Autowired
//    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = null;
        try {
            user = userService.selectUserByUserName(username);
        }catch (Exception e){
            throw new RuntimeException("发生错误:"+e.getMessage());
        }
        if (StringUtils.isNull(user)) {
            // 用户不存在错误标识
            throw new RuntimeException("user_not_exist");
        }
        else if (UserStatus.DELETED.getCode().equals(user.getDelFlag().toString())) {
            // 用户已被删除错误标识
            throw new RuntimeException("user_by_delete");
        }
        else if (UserStatus.DISABLE.getCode().equals(user.getStatus().toString())) {
            // 用户已被停用错误标识
            throw new RuntimeException("user_by_stop");
        }
        // 自定义密码校验，限制密码错误次数锁定账号
        passwordService.validate(user);
        return new LoginUser(user,new ArrayList<>());

    }
}
